from odoo import fields, models, api

SOURCE_TYPE = [('order', '下单'), ('login', '登录'), ('invite', '邀请')]
CUSTOMER_CATEGORY = [('personal', '个人'), ('company', '公司'), ('manage', '管理'), ('other', '其他')]


class RPCustomer(models.Model):
    _name = 'rp.customer'
    _description = '客户'
    _inherit = ['mail.thread', 'mail.activity.mixin']

    # 基本信息
    name = fields.Char(string='名称', index=True, copy=False,
                       compute='_depends_customer_category', store=True, readonly=False)
    last_name = fields.Char(string='姓')
    first_name = fields.Char(string='名')
    area_code = fields.Char(string='区号')
    phone_number = fields.Char(string='手机号', copy=False, index=True)
    email = fields.Char(string='注册邮箱', index=True, copy=False)
    google_email = fields.Char(string='google邮箱')
    birthday_date = fields.Date(string='生日', copy=False, index=True)
    source_type = fields.Selection(string='来源', selection=SOURCE_TYPE)
    rp_customer_category = fields.Many2one(string='客户分类', comodel_name='rp.customer.category', copy=False)
    customer_level = fields.Many2one(string='客户等级', comodel_name='rp.customer.level', copy=False, index=True)
    customer_category = fields.Selection(string='类别', selection=CUSTOMER_CATEGORY, default=CUSTOMER_CATEGORY[0][0])
    address_ids = fields.One2many(string='地址', comodel_name='res.partner', inverse_name='customer_address_id')
    contact_ids = fields.One2many(string='联系人', comodel_name='res.partner', inverse_name='customer_contact_id')
    profile_image = fields.Binary(string='头像', attachment=True)

    # 安全信息
    username = fields.Char(string='账号')
    password = fields.Char(string='密码')

    # 财务相关信息
    remaining_sum = fields.Float(string='余额', copy=False, related='rp_customer_balance_id.total_balance', index=True, store=True)
    rp_customer_balance_id = fields.Many2one(string='客户余额', comodel_name='rp.customer.balance')
    flow_log_ids = fields.One2many(string='流水', comodel_name='rp.flow.log', inverse_name='rp_customer_id', copy=False)
    currency_id = fields.Many2one(string='货币单位', comodel_name='res.currency', default=lambda self: self.env.company.currency_id)

    active = fields.Boolean(string='有效', default=True)

    """
    Native Method
    """

    @api.model_create_multi
    def create(self, vals_list):
        """
        创建客户时，如果没有账号密码，则默认将邮箱设定为账号，将ID设置为密码
        """
        res = self
        for vals in vals_list:
            username = vals.get('username', False)
            password = vals.get('password', False)
            result = super(RPCustomer, self).create([vals])
            if any([not username, not password]):
                username = result.email if result.email else result.id
                password = result.id
            # 创建余额表
            rp_customer_balance_id = self.env['rp.customer.balance'].create({'rp_customer_id': result.id})
            result.write({'username': username, 'password': password, 'rp_customer_balance_id': rp_customer_balance_id.id})
            res |= result
        return res

    def name_get(self):
        result = []
        for record in self:
            if record._context.get('show_display'):
                result.append((record.id, '{} ( {} € )'.format(record.name, record.rp_customer_balance_id.total_balance)))
            else:
                result.append((record.id, record.name))
        return result

    """
    Depends
    """

    @api.depends('customer_category', 'last_name', 'first_name')
    def _depends_customer_category(self):
        for s in self:
            if s.customer_category == CUSTOMER_CATEGORY[0][0]:
                if s.last_name and s.first_name:
                    s.update({'name': s.first_name + ' ' + s.last_name})

    """
    Button Function
    """

    @api.model
    def action_generate_balance(self):
        """
        生成余额表
        """
        rp_customer_ids = self.env['rp.customer'].search([])
        for record in rp_customer_ids:
            if not record.rp_customer_balance_id:
                rp_customer_balance_id = self.env['rp.customer.balance'].search([('rp_customer_id', '=', record.id)])
                if not rp_customer_balance_id:
                    rp_customer_balance_id = self.env['rp.customer.balance'].create({'rp_customer_id': record.id})
                record.write({'rp_customer_balance_id': rp_customer_balance_id.id})
